package com.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: study
 * @className: Solution349
 * @description: TODO
 * @author: kukuxiahuni
 * @create: 2020-02-06 16:11
 **/
public class Solution349 {

    public static void main(String[] args) {
        int[] nums1 = {4, 9, 5};
        int[] nums2 = {9, 4, 9, 8, 4};

        Solution349 solution349 = new Solution349();
        int[] result = solution349.intersection(nums1, nums2);
        for (int n : result) {
            System.out.println(n);
        }
    }

    public int[] intersection(int[] nums1, int[] nums2) {

        Arrays.sort(nums1);
        Arrays.sort(nums2);

        Set<Integer> set = new HashSet<>();
        int i = 0, j = 0;

        while (i < nums1.length && j < nums2.length) {

            if (nums1[i] == nums2[j]) {
                ++i;
                ++j;
                set.add(nums1[i]);
            } else if (nums1[i] > nums2[j]) {
                ++j;
            } else {
                ++i;
            }
        }

        int[] array = new int[set.size()];
        int index = 0;

        for (int n : set) {
            array[index++] = n;
        }

        return array;

    }

    public int[] intersection1(int[] nums1, int[] nums2) {

        Arrays.sort(nums1);
        Set<Integer> resultSet = new HashSet<>();
        for (int n : nums2) {
            if (bsearch(nums1, n)) {
                resultSet.add(n);
            }
        }

        int[] array = new int[resultSet.size()];
        int index = 0;
        for (int n : resultSet) {
            array[index++] = n;
        }

        return array;

    }

    private final boolean bsearch(int[] array, int target) {

        int start = 0, end = array.length - 1;

        while (start <= end) {
            int mid = start + (end - start) / 2;

            if (array[mid] == target) {
                return true;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return false;
    }
}
